<template>
    <u-navbar
        title="立即下单"
        title-color="black"
        back-icon-color="black"
        :title-bold="true"
    ></u-navbar>
    <view class="process-section">
        <view class="process-title">回收流程</view>
        <view class="process-list">
            <u-grid :col="4" class="process-item" :border="false">
                <u-grid-item>
                    <view class="row-between">
                        <view class="column-center">
                            <image :src="imageUrl.yuyue" mode="aspectFill"></image>
                            <view class="grid-text">在线预约</view>
                        </view>
                        <view class="grid-right-icon">
                            <u-icon name="arrow-right" class="row-center" />
                        </view>
                    </view>
                </u-grid-item>
                <u-grid-item>
                    <view class="row-between">
                        <view class="column-center">
                            <image :src="imageUrl.shangmen" mode="aspectFill"></image>
                            <view class="grid-text">免费上门</view>
                        </view>
                        <view class="grid-right-icon">
                            <u-icon name="arrow-right" class="row-center" />
                        </view>
                    </view>
                </u-grid-item>
                <u-grid-item>
                    <view class="row-between">
                        <view class="column-center">
                            <image :src="imageUrl.wancheng" mode="aspectFill"></image>
                            <view class="grid-text">订单完成</view>
                        </view>
                        <view class="grid-right-icon">
                            <u-icon name="arrow-right" class="row-center" />
                        </view>
                    </view>
                </u-grid-item>
                <u-grid-item>
                    <view class="row-between">
                        <view class="column-center">
                            <image :src="imageUrl.shouyi" mode="aspectFill"></image>
                            <view class="grid-text">获取收益</view>
                        </view>
                        <view class="grid-right-icon"></view>
                    </view>
                </u-grid-item>
            </u-grid>
        </view>
    </view>
    <view class="category-section">
        <view class="section-header">
            <text class="label bold label-title">回收类别</text>
            <text class="label alert-label">可打包在一起回收哦</text>
        </view>
        <view class="category-list">
            <u-grid :col="4" class="category-item" :border="false">
                <u-grid-item v-for="item in categoryList" :key="item.id">
                    <image :src="item.image" mode="aspectFill" />
                    <text class="bold">{{ item.cate_name }}</text>
                </u-grid-item>
            </u-grid>
        </view>
    </view>
    <view class="form-section">
        <view class="form-title">免费上门取件</view>
        <view class="process-form">
            <u-form :model="formData" :rules="rules" ref="formRef" label-width="180rpx">
                <u-form-item
                    label="取件地址"
                    prop="pickup_address"
                    :border-bottom="false"
                    class="ml20"
                >
                    <u-input
                        v-model="formData.pickup_address"
                        placeholder="请输入取件地址"
                        class="u-border-bottom mr20"
                    />
                </u-form-item>
                <u-form-item
                    label="取件时间"
                    prop="pickup_time"
                    :border-bottom="false"
                    class="ml20"
                >
                    <view @click="date_show = true" class="flex flex-1 row-between">
                        <u-input
                            v-model="formData.pickup_time"
                            disabled
                            placeholder="请选择取件时间"
                            class="u-border-bottom"
                        />
                        <u-picker
                            v-model="date_show"
                            mode="time"
                            :params="params"
                            @confirm="onDateConfirm"
                        />
                        <u-icon name="arrow-right" size="28" color="#999" />
                    </view>
                </u-form-item>
                <u-form-item
                    label="联系方式"
                    prop="contact_number"
                    :border-bottom="false"
                    class="ml20"
                >
                    <u-input
                        v-model="formData.contact_number"
                        placeholder="请输入联系方式"
                        class="u-border-bottom mr20"
                    />
                </u-form-item>
                <u-form-item label="留言备注" prop="remark" :border-bottom="false" class="ml20">
                    <u-input
                        v-model="formData.remark"
                        placeholder="请输入备注 (选填)"
                        class="u-border-bottom mr20"
                    />
                </u-form-item>
                <u-form-item
                    label="预估重量"
                    prop="estimated_weight"
                    :border-bottom="false"
                    class="ml20"
                >
                    <view class="flex1 row-end mr20" @click="showPopup = true">
                        <u-icon
                            label="回收标准"
                            :name="imageUrl.alertImg"
                            size="32"
                            label-pos="left"
                        ></u-icon>
                    </view>
                </u-form-item>
                <u-form-item>
                    <!-- 自定义选项卡样式 -->
                    <view class="weight-options">
                        <view
                            v-for="(option, index) in weightOptions"
                            :key="index"
                            class="weight-option column-center"
                            :class="{ active: selectedIndex === index, disabled: index === 0 }"
                            @click="index !== 0 && selectWeight(index)"
                        >
                            <text class="criteria-text">{{ option.criteria }}</text>
                            <text>{{ option.label }}</text>
                            <view v-if="selectedIndex === index" class="check-wrapper">
                                <u-icon name="checkmark" color="white" size="20"></u-icon>
                            </view>
                        </view>
                    </view>
                </u-form-item>
                <u-form-item label="" prop="agree_terms" :border-bottom="false" class="ml20">
                    <view class="row-start agree-section">
                        <u-checkbox
                            v-model="formData.agree_terms"
                            :value="formData.agree_terms"
                            name="agree_terms"
                            active-color="#2979ff"
                            shape="circle"
                            @change="checkboxChange"
                        ></u-checkbox>
                        <text class="agree-text">我已阅读并同意</text>
                        <text class="agree-link" @click.stop="showTerms">《回收服务条款》</text>
                    </view>
                </u-form-item>
                <view class="faq-section">
                    <view class="faq-header">
                        <text class="label bold label-title">常见问题</text>
                    </view>
                    <u-collapse>
                        <u-collapse-item
                            v-for="(item, index) in articleList"
                            :key="index"
                            title="item.title"
                            :open="item.isOpen"
                        >
                            <template v-slot:title>
                                <view class="title-box">
                                    <u-icon
                                        name="question-circle-fill"
                                        :size="32"
                                        color="#aeb3bd"
                                    />
                                    {{ item.title }}
                                </view>
                            </template>
                            <view class="show-box"> {{ item.description }}</view>
                        </u-collapse-item>
                    </u-collapse>
                </view>
                <button class="book-btn commit_btn" @click="submitBooking" :disabled="isSubmitting"  :class="{ 'btn-disabled': isSubmitting }"> {{ isSubmitting ? '提交中...' : '立即预约回收' }}</button>
            </u-form>
        </view>
    </view>
    <u-popup
        v-model="showPopup"
        mode="center"
        :closeable="true"
        :border-radius="16"
        close-icon-color="#ffffff"
    >
        <view class="popup-content">
            <view class="popup-title">回收标准</view>
            <view class="standard-list">
                <view class="standard-section">
                    <view class="standard-title">
                        <view class="title-text">
                            <text>回收标准</text>
                        </view>
                    </view>
                    <view class="standard-content">
                        <rich-text :nodes="standard[1]?.content"></rich-text>
                    </view>
                </view>
                <view class="standard-section">
                    <view class="standard-title">
                        <view class="title-text">
                            <text>回收价格</text>
                        </view>
                    </view>
                    <view class="standard-content">
                        <rich-text :nodes="standard[0]?.content"></rich-text>
                    </view>
                </view>
            </view>
        </view>
    </u-popup>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad, onPageScroll, onReady } from '@dcloudio/uni-app'
import { getCateList, getIndex } from '@/api/shop'
import { apiCreateOrder } from '@/api/order'
import config from '@/config'
import { useAppStore } from '@/stores/app'
import { apiStandard } from '@/api/news'
import { getPolicy } from '@/api/app'
const isSubmitting = ref(false)
const { getImageUrl } = useAppStore()
const imageUrl = ref({
    yuyue: config.baseUrl + '/static/images/yuyue.png',
    shangmen: config.baseUrl + '/static/images/shangmen.png',
    wancheng: config.baseUrl + '/static/images/wancheng.png',
    shouyi: config.baseUrl + '/static/images/shouyi.png',
    alertImg: config.baseUrl + '/static/images/alert_icon.png'
})

const formRef = ref(null)
const scrollTop = ref<number>(0)
const percent = ref<number>(0)
const date_show = ref(false)
const showPopup = ref(false)
const params = ref({
    year: true,
    month: true,
    day: true,
    hour: true
})

const standard = ref([])
const getStandard = async () => {
    try {
        standard.value = await apiStandard()
    } catch (error) {
        console.error('获取标准列表失败:', error)
    }
}

const travelDate = ref({
    year: new Date().getFullYear(),
    month: pad(new Date().getMonth() + 1),
    day: pad(new Date().getDate()),
    hour: pad(new Date().getHours()),
    minute: pad(new Date().getMinutes())
})

function pad(n) {
    return n < 10 ? '0' + n : n
}

const onDateConfirm = (value) => {
    travelDate.value = value
    let hour = parseInt(travelDate.value.hour)
    hour += 1
    let newHour = hour
    formData.pickup_time = `${value.year}-${value.month}-${value.day} ${value.hour}` + `:00`
}

// 模拟后台返回的分类数据
const categoryList = ref([])

const getCategoryList = async () => {
    try {
        const data = await getCateList()

        if (!Array.isArray(data)) {
            console.warn('getBanner 返回非数组数据:', data)
            return
        }

        data.forEach((item) => {
            item.image = getImageUrl(item.ico_image)
        })
        categoryList.value = data
    } catch (error) {
        console.error('获取分类列表失败:', error)
        uni.showToast({ title: '加载分类列表失败', icon: 'none' })
    }
}

const rules = {
    pickup_address: [{ required: true, message: '请输入取件地址', trigger: 'blur' }],
    pickup_time: [{ required: true, message: '请选择取件时间', trigger: 'blur' }],
    contact_number: [
        { required: true, message: '请输入手机号' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
    ],
    estimated_weight: [{ required: false, message: '请输入预估重量', trigger: 'blur' }],
    agree_terms: [
        {
            validator: (rule, value, callback) => {
                if (!formData.agree_terms) {
                    callback(new Error('请勾选我已阅读并同意'))
                } else {
                    callback()
                }
            },
            message: '请勾选我已阅读并同意',
            trigger: ['change']
        }
    ]
}

const formData = reactive({
    pickup_address: '',
    pickup_time: '',
    remark: '',
    mobile: '',
    estimated_weight: '',
    agree_terms: false,
    contact_number: ''
})

const resetFormData = () => {
    // 重置表单字段
    formData.pickup_address = ''
    formData.pickup_time = ''
    formData.remark = ''
    formData.estimated_weight = ''
    formData.agree_terms = false
    formData.contact_number = ''

    // 重置时间选择器
    travelDate.value = {
        year: new Date().getFullYear(),
        month: pad(new Date().getMonth() + 1),
        day: pad(new Date().getDate()),
        hour: pad(new Date().getHours()),
        minute: pad(new Date().getMinutes())
    }
    // date_show.value = false;

    // 重置预估重量选择
    selectedIndex.value = 1
    formData.estimated_weight = weightOptions[selectedIndex.value].criteria

    // 重置条款勾选状态
    formData.agree_terms = false
}

const weightOptions = [
    { label: '暂不回收', criteria: '10kg以下' },
    { label: '约10-50件', criteria: '10-30kg' },
    { label: '约50-100件', criteria: '30-50kg' },
    { label: '100件以上', criteria: '50kg以上' }
]

const checkboxChange = (event) => {
    formData.agree_terms = event.value
}

// 当前选中的索引
const selectedIndex = ref<number>(1)

// 处理点击事件
const selectWeight = (index: number) => {
    selectedIndex.value = index
    formData.estimated_weight = weightOptions[selectedIndex.value].criteria
}
const service = ref('')
const getService = async () => {
    try {
        const res = await getPolicy({ type: 'service' })
        service.value = res.description
    } catch (error) {
        console.error('获取服务失败:', error)
        // uni.showToast({ title: '加载服务失败', icon: 'none' })
    }
}

const showTerms = (event) => {
    uni.showModal({
        title: '回收服务条款',
        content: service.value,
        success: (res) => {
            if (res.confirm) {
                // 用户点击确定 → 勾选复选框
                formData.agree_terms = true
            } else if (res.cancel) {
                // 用户点击取消 → 取消勾选
                formData.agree_terms = false
            }
        },
        confirmColor: '#2979ff'
    })
}

const articleList = ref([])

const getData = async () => {
    try {
        const data = await getIndex()
        // 校验数据有效性并深拷贝
        const validData = Array.isArray(data) ? JSON.parse(JSON.stringify(data)) : []

        validData.map((item, index) => {
            if (index === 0) {
                item.isOpen = true
            }
            return item // 确保 map 返回新数组
        })

        articleList.value = validData
    } catch (error) {
        console.error('获取数据失败:', error)
        articleList.value = [] // 异常时赋默认值
    }
    formData.estimated_weight = weightOptions[selectedIndex.value].criteria
}

onReady(() => {
    formRef.value.setRules(rules)
})

const submitBooking = async () => {
  // 立即设置提交状态，防止重复点击
  if (isSubmitting.value) return
  isSubmitting.value = true
    try {
      // 使用 promise 包装 validate 方法以确保正确处理异步验证
      await new Promise((resolve, reject) => {
        formRef.value.validate(async (valid) => {
          if (valid) {
            try {
              const res = await apiCreateOrder(formData)
              resetFormData()
              uni.showToast({ title: '提交成功', icon: 'success' })

              uni.switchTab({ url: '/pages/order/order' })
              // 可选：重置表单验证状态
              if (formRef.value?.resetFields) {
                formRef.value.resetFields()
              }
              resolve(res)
            } catch (error) {
              reject(error)
            }
          } else {
            reject(new Error('表单验证失败'))
          }
        })
      })
    } catch (error) {
        uni.showToast({ title: '请检查表单内容', icon: 'none' })
    } finally {
      // 无论成功还是失败都结束提交状态
      isSubmitting.value = false
    }
}

// 页面滚动事件
onPageScroll((event: any) => {
    scrollTop.value = event.scrollTop
    const top = uni.upx2px(100)
    percent.value = event.scrollTop / top > 1 ? 1 : event.scrollTop / top
})

// 页面加载
onLoad(() => {
    getData()
    getCategoryList()
    getStandard()
    getService()
})
</script>
<style scoped lang="scss">
.process-section {
    margin: 20rpx;
    height: auto; /* 设置固定高度 */
    background-image: linear-gradient(to bottom, #dee8fe, #ffffff); /* 添加渐变 */
    background-color: #ffffff;
    background-repeat: no-repeat;
    background-size: 100% 20%;
    padding: 0 20rpx;
    border-radius: 16rpx;

    .process-title {
        display: flex;
        font-weight: bold;
        padding-top: 40rpx;
        margin-left: 10rpx;
        font-size: 34rpx;
    }

    .process-list {
        display: flex;
        margin-top: 20rpx;

        .process-item {
            text-align: center;
            font-size: 26rpx;
            flex-shrink: 0;

            image {
                width: 80rpx;
                height: 80rpx;
            }

            .grid-text {
                margin-top: 20rpx;
                color: #000000;
                font-weight: 400;
            }

            .grid-right-icon {
                margin-left: 20rpx;
                margin-top: -20rpx;
            }
        }
    }

    .step {
        flex-direction: column;
        align-items: center;
    }

    .u-icon {
        margin-bottom: 20rpx;
    }
}

.category-section {
    position: relative;
    padding: 20rpx;
    height: auto; /* 设置固定高度 */
    background-image: linear-gradient(to bottom, #dee8fe, #ffffff); /* 添加渐变 */
    background-color: #ffffff;
    background-repeat: no-repeat;
    background-size: 100% 20%;
    z-index: 999;
    margin: 20rpx;
    border-radius: 16rpx;
}

.section-header {
    margin-top: 20rpx;
    margin-bottom: 20rpx;

    .label {
        font-size: 28rpx;
    }

    .label-title {
        margin-left: 10rpx;
        font-size: 34rpx;
    }

    .alert-label {
        border: 0.1rpx solid #236af6;
        background: #f6f9ff;
        color: #236af6;
        font-size: 24rpx;
        padding: 5rpx;
        border-radius: 6rpx;
        margin-left: 20rpx;
    }
}

.category-list {
    display: flex;
    overflow-x: auto;
    white-space: nowrap;
    padding: 0 20rpx;
}

.category-item {
    margin-right: 20rpx;
    text-align: center;
    font-size: 26rpx;
    flex-shrink: 0;

    image {
        width: 110rpx;
        height: 80rpx;
        border-radius: 16rpx;
        margin-bottom: 10rpx;
    }
}

.process-form {
    margin-left: 10rpx;
}

.weight-options {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    width: 120%;
    flex: 1;
}

.weight-option {
    position: relative;
    width: 23.5%;
    padding: 20rpx 0;
    border: 1rpx solid #ddd;
    border-radius: 16rpx;
    color: #666;
}

.weight-option.active {
    border-color: #2979ff;

    .check-wrapper {
        padding: 20rpx 20rpx 5rpx 30rpx;
        position: absolute;
        bottom: 0;
        right: 0;
        width: 30rpx;
        height: 35rpx;
        background-color: #2979ff;
        border-radius: 100rpx 0 0;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 0 6rpx rgba(0, 0, 0, 0.1);
        z-index: 2;
        transition: all 0.3s ease;
    }
}

.form-section {
    position: relative;
    padding: 20rpx 0;
    height: auto; /* 设置固定高度 */
    background-image: linear-gradient(to bottom, #dee8fe, #ffffff); /* 添加渐变 */
    background-color: #ffffff;
    background-repeat: no-repeat;
    background-size: 100% 20%;
    z-index: 999;
    margin: 20rpx;
    border-radius: 16rpx;
}

.form-title {
    display: flex;
    font-weight: bold;
    padding-top: 40rpx;
    margin-left: 30rpx;
    font-size: 34rpx;
}

.criteria-text {
    color: #2979ff;
    font-weight: bold;
}

.agree-link {
    color: #2979ff;
}

.faq-section {
    margin: 0 20rpx 20rpx;
    height: auto; /* 设置固定高度 */
    background-image: linear-gradient(to bottom, #dee8fe, #ffffff); /* 添加渐变 */
    background-color: #ffffff;
    background-repeat: no-repeat;
    background-size: 100% 30%;
    padding: 0 20rpx;
    border-radius: 16rpx;
}

.faq-header {
    padding: 40rpx 0 20rpx 10rpx;
}

.quick-action-button {
    background-image: url('{{config.baseUrl}}/static/images/quick-action-button.png');
    background-size: cover;
    background-repeat: no-repeat;
    height: 150rpx;
    width: 714rpx;
}

.title-box {
    margin-left: 10rpx;
    font-weight: bold;
}

.title-text {
    margin-left: 15rpx;
    font-size: 26rpx;
    font-weight: 500;
}

.show-box {
    padding: 20rpx;
    background-color: #f9f9f9;
    border-radius: 10rpx;
    margin-bottom: 20rpx;
}

.disabled {
    color: #ccc; // 灰色文字
    pointer-events: none; // 阻止点击
}

.popup-content {
    background-color: #2979ff;
    border-radius: 16rpx;
    width: 700rpx;
}

.standard-list {
    background-color: #ffffff;
    padding: 30rpx 40rpx;
    border-radius: 16rpx;
    line-height: 45rpx;
    font-size: 26rpx;
}

.popup-title {
    text-align: center;
    font-size: 34rpx;
    color: #ffffff;
    line-height: 100rpx;
}

.title-text {
    color: #2979ff;
    font-weight: bold;
    font-size: 26rpx;
}

.book-btn {
  background-color: #2979ff;
  color: white;
  border: none;
  transition: all 0.3s ease;
  /* 其他原有样式 */
}

.book-btn.btn-disabled {
  background-color: #cccccc !important;
  color: #ffffff !important;
  opacity: 0.6;
  cursor: not-allowed;
}

.book-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
